// http server logic
const express = require("express");
const app = express();
const request = require('request');
const fs = require("fs");
const ps = require("process");
const http = require("http");
var q = require("q");

Date.prototype.Format = function (fmt) { //author: meizz   
    var o = {
        "M+": this.getMonth() + 1,                 //月份   
        "d+": this.getDate(),                    //日   
        "h+": this.getHours(),                   //小时   
        "m+": this.getMinutes(),                 //分   
        "s+": this.getSeconds(),                 //秒   
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
        "S": this.getMilliseconds()             //毫秒   
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

app.get('/now', function (req, resp) {
    request('http://himawari8-dl.nict.go.jp/himawari8/img/D531106/latest.json', function (error, response, body) {
        var val = eval("(" + body + ")");
        var str = val.date;
        //http://himawari8-dl.nict.go.jp/himawari8/img/D531106/1d/550/2016/09/29/055000_0_0.png
        var dp = str.replace(/-/g, "/").replace(/:/g, '').replace(/ /g, '/');
        var sp = str.replace(/-/g, "_").replace(/:/g, '').replace(/ /g, '-');
        var imgUrl = "http://himawari8-dl.nict.go.jp/himawari8/img/D531106/1d/550/" + dp + "_0_0.png";
        var savePath = ps.cwd() + "/app/static/imgs/" + sp + "_0_0.png";
        var result = '{"name":"' + '/imgs/' + sp + '_0_0.png", "time":"' + str + '"}';
        fs.exists(savePath, function (exists) {
            if (!exists) {
                var file = fs.createWriteStream(savePath);
                http.get(imgUrl, function (response) {
                    response.pipe(file);
                    file.on('finish', function () {
                        file.close();
                        resp.send(result);
                    });
                });
            } else {
                fs.stat(savePath, function (err, st) {
                    console.log("fs size: " + st.size);
                    if (st.size < 1024 * 100) {
                        var file = fs.createWriteStream(savePath);
                        http.get(imgUrl, function (response) {
                            response.pipe(file);
                            file.on('finish', function () {
                                file.close();
                                resp.send(result);
                            });
                        });
                    } else resp.send(result);
                });
            }
        });
    });
});

var downloadImg = function (imgUrl, localPath) {
    return function () {
        var def = q.defer();
        http.get(imgUrl, function (response) {
            var file = fs.createWriteStream(localPath);
            response.pipe(file);
            file.on('finish', function () {
                file.close();
                console.log("Image: " + imgUrl + " Successful");
                def.resolve();
            });
        });
        return def.promise;
    };
};

app.get('/all', function (req, resp) {
    var t = new Date();
    var y = t.getFullYear();
    var m = t.getMonth();
    var d = t.getDate();
    var h = t.getHours();
    t = new Date(y, m, d, h - 8);
    var nt = 0;
    var needDownloads = [];
    while (true) {
        var base = new Date(y, m, d, 0 - 8, nt);
        if (base > t) {
            break;
        }
        nt = nt + 10;
        var savePath = ps.cwd() + "/app/static/imgs/" + base.Format("yyyy_MM_dd-hhmm") + "00_0_0.png";
        console.log(savePath);
        var netPath = base.Format("yyyy/MM/dd/hhmm00_0_0.png");
        if (!fs.existsSync(savePath)) {
            needDownloads.push({ "local": savePath, "net": netPath });
        }
    }
    console.log(needDownloads.length);
    var queue = q();
    needDownloads.forEach(function (ele) {
        var localPath = ele.local;
        var netPath = ele.net;
        var imgUrl = "http://himawari8-dl.nict.go.jp/himawari8/img/D531106/1d/550/" + netPath;
        queue = queue.then(downloadImg(imgUrl, localPath));
    });
    queue.then(function () {
        resp.send("文件下载完毕");
    });
});

app.get('/dynamic', function (req, resp) {
    var dir = ps.cwd() + "/app/static/imgs";
    fs.readdir(dir, function (err, files) {
        if (err) {
            resp.send("[]");
            return;
        }
        resp.send(files);
    });
});

app.start = function () {
    console.log("server starting");
    app.listen(8923, function () {
        console.log("server is listing");
    });
};

module.exports = app;